"""Utilities for selecting and loading models."""
import contextlib
from typing import Tuple, Type

import torch
from torch import nn

from vllm.config import ModelConfig
from vllm.model_executor.models import ModelRegistry
from vllm.model_executor.models.adapters import (as_classification_model,
                                                 as_embedding_model,
                                                 as_reward_model)


@contextlib.contextmanager
def set_default_torch_dtype(dtype: torch.dtype):
    """Sets the default torch dtype to the given dtype."""
    old_dtype = torch.get_default_dtype()
    torch.set_default_dtype(dtype)
    yield
    torch.set_default_dtype(old_dtype)


def get_model_architecture(
        model_config: ModelConfig) -> Tuple[Type[nn.Module], str]:
    architectures = getattr(model_config.hf_config, "architectures", [])
    #  model_config.hf_config ==> LlamaConfig


    # Special handling for quantized Mixtral.
    # FIXME(woosuk): This is a temporary hack.
    mixtral_supported = [         #! mixtral模型当前支持量化格式
        "fp8", "compressed-tensors", "gptq_marlin", "awq_marlin"
    ]

    # swift/Meta-Llama-3-8B-Instruct-AWQ:  quantization => awq_marlin
    if (model_config.quantization is not None
            and model_config.quantization not in mixtral_supported
            and "MixtralForCausalLM" in architectures):
        architectures = ["QuantMixtralForCausalLM"]    #! 特殊处理

    # arch: swift/Meta-Llama-3-8B-Instruct-AWQ:    LlamaForCausalLM
    #       AI-ModelScope/e5-mistral-7b-instruct:  MistralModel
    # task: swift/Meta-Llama-3-8B-Instruct-AWQ     generate
    #       AI-ModelScope/e5-mistral-7b-instruct   generate(default)  需要手动指定为embed
    model_cls, arch = ModelRegistry.resolve_model_cls(architectures)
    if model_config.task == "embed":
        model_cls = as_embedding_model(model_cls)
    elif model_config.task == "classify":
        model_cls = as_classification_model(model_cls)
    elif model_config.task == "reward":
        model_cls = as_reward_model(model_cls)

    return model_cls, arch


def get_architecture_class_name(model_config: ModelConfig) -> str:
    return get_model_architecture(model_config)[1]

# modelscope download --model AI-ModelScope/e5-mistral-7b-instruct --local_dir AI-ModelScope/e5-mistral-7b-instruct --exclude "*.bin"